package battlebarnserver;

import battlebarnapplet.ClientStart;
import battlebarnserver.BattleBarn;
import battlebarnserver.entities.InanimateEntity;
import battlebarnserver.util.Conversions;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author johncreecy
 */
public class ClientSignOnThread implements Runnable {

	private String targetIp;

	public ClientSignOnThread(String ip) {
		targetIp = ip;
	}

	private void sendSignOnData() {
		DatagramPacket sendPacket;
		Long timeStamp;
		String outData;
		byte[] gameData;
		String xPad = "000";
		String yPad = "000";
		InanimateEntity inanimateEntity;
		DatagramSocket clientSocket;
		InetAddress IPAddress;
		for (int i = 0; i < BattleBarn.staticGameData.size(); i++) {
			try {
				outData = "";
				timeStamp = (long) (System.currentTimeMillis());
				gameData = new byte[1024];
				clientSocket = new DatagramSocket();
				inanimateEntity = BattleBarn.staticGameData.get(i);
				xPad = Conversions.padCoordinate(Integer.toString(Conversions.tileToPixel(inanimateEntity.getTileX())));
				yPad = Conversions.padCoordinate(Integer.toString(Conversions.tileToPixel(inanimateEntity.getTileY())));
				outData = timeStamp + xPad + yPad + "i";
				gameData = outData.getBytes();
				IPAddress = InetAddress.getByName(targetIp);
				sendPacket = new DatagramPacket(gameData, gameData.length, IPAddress, ClientStart.clientPort);
				clientSocket.send(sendPacket);
				BattleBarn.packetsOut++;
			} catch (IOException ex) {
				Logger.getLogger(StateGenerator.class.getName()).log(Level.SEVERE, null, ex);
			}
		}
	}

	public void run() {
		sendSignOnData();
	}
}
